package com.example.hobbyplanetserve.config;


import com.example.hobbyplanetserve.filter.JwtAuthenticationTokenFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Arrays;

import static org.springframework.security.config.Customizer.withDefaults;

@Configuration //配置类
@EnableWebSecurity //开启Spring Security自定义配置 （在spring boot项目中可以省略）
public class WebSecurityConfig{

    @Autowired
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                .csrf(csrf -> csrf.disable())  // 使用 Lambda 风格禁用 CSRF
                .authorizeHttpRequests(authorize -> authorize
                        .requestMatchers("/api/users/login").permitAll() // 允许登录接口访问
                        .anyRequest().authenticated() // 所有请求需要认证
                )
                .cors(cors->{
                    cors.configurationSource(corsConfigurationSource());
                })

        //自定义过滤器放在UsernamePasswordAuthenticationFilter过滤器之前
                .addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class)
                .formLogin(withDefaults()); // 开启表单登录
        return http.build();
    }

    /*
     * 验证管理器
     * */
    @Bean
    public AuthenticationManager authenticationManager(PasswordEncoder passwordEncoder){
        DaoAuthenticationProvider provider=new DaoAuthenticationProvider();
        //将编写的UserDetailsService注入进来
        provider.setUserDetailsService(userDetailsService());
        //将使用的密码编译器加入进来
        provider.setPasswordEncoder(passwordEncoder);
        //将provider放置到AuthenticationManager 中
        ProviderManager providerManager=new ProviderManager(provider);
        return providerManager;
    }


    //跨域配置
    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        //设置允许跨域请求的域名
        configuration.setAllowedOrigins(Arrays.asList("*"));
        //设置允许跨域请求的请求方式
        configuration.setAllowedMethods(Arrays.asList("*"));
        //设置允许跨域请求的头部信息
        configuration.setAllowedHeaders(Arrays.asList("*"));
        //将CORS配置应用于特定的URL，"/**"表示对所有URL都应用CORS配置
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

    /**
     * 自定义用户信息管理器 userDetailsService用来管理用户信息
     * @return
     */
    @Bean
    public UserDetailsService userDetailsService() {
        //基于数据库的用户信息管理器
        DBUserDetailsManager manager = new DBUserDetailsManager();
        return manager;
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder(); // 使用 BCrypt 加密
    }

}
